package com.xmtlxx.tms.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.xmtlxx.common.core.domain.PageQuery;
import com.xmtlxx.common.core.page.TableDataInfo;
import com.xmtlxx.common.utils.DateUtils;
import com.xmtlxx.common.utils.StringUtils;
import com.xmtlxx.tms.domain.Schedule;
import com.xmtlxx.tms.domain.ScheduleDtl;
import com.xmtlxx.tms.domain.bo.ScheduleBo;
import com.xmtlxx.tms.domain.vo.CarrierVo;
import com.xmtlxx.tms.domain.vo.ScheduleDtlVo;
import com.xmtlxx.tms.domain.vo.ScheduleVo;
import com.xmtlxx.tms.mapper.*;
import com.xmtlxx.tms.service.IScheduleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 车次Service业务层处理
 *
 * @author xmtlxx
 * @date 2022-08-15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class ScheduleServiceImpl implements IScheduleService {

    private final ScheduleMapper baseMapper;

    private final ScheduleDtlMapper scheduleDtlMapper;

    private final CarMapper carMapper;

    private final DriverMapper driverMapper;

    private final CarrierMapper carrierMapper;

    /**
     * 查询车次
     *
     * @param id 车次主键
     * @return 车次
     */
    @Override
    public ScheduleVo queryById(String id){
        //return baseMapper.selectVoById(id);
        return baseMapper.selectScheduleVoByID(id);
    }

    /**
     * 查询车次列表
     *
     * @param bo 车次
     * @return 车次
     */
    @Override
    public TableDataInfo<ScheduleVo> queryPageList(ScheduleBo bo, PageQuery pageQuery) {
       // LambdaQueryWrapper<Schedule> lqw = buildQueryWrapper(bo);
       // Page<ScheduleVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        Page<ScheduleVo> result = baseMapper.selectPageScheduleList(pageQuery.build(), bo);
        return TableDataInfo.build(result);
    }

    /**
     * 查询车次列表
     *
     * @param bo 车次
     * @return 车次
     */
    @Override
    public List<ScheduleVo> queryList(ScheduleBo bo) {
       // LambdaQueryWrapper<Schedule> lqw = buildQueryWrapper(bo);
       // return baseMapper.selectVoList(lqw);
        return baseMapper.selectScheduleList(bo);
    }

    private LambdaQueryWrapper<Schedule> buildQueryWrapper(ScheduleBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Schedule> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCarrierId()), Schedule::getCarrierId, bo.getCarrierId());
        lqw.eq(bo.getDeptId() != null, Schedule::getDeptId, bo.getDeptId());
        lqw.like(StringUtils.isNotBlank(bo.getName()), Schedule::getName, bo.getName());
        lqw.eq(bo.getDay() != null, Schedule::getDay, bo.getDay());
        lqw.eq(StringUtils.isNotBlank(bo.getLineId()), Schedule::getLineId, bo.getLineId());
        lqw.eq(StringUtils.isNotBlank(bo.getStatus()), Schedule::getStatus, bo.getStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getDelFlag()), Schedule::getDelFlag, bo.getDelFlag());
        return lqw;
    }

    /**
     * 新增车次
     *
     * @param bo 车次
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean insertByBo(ScheduleBo bo) {
        boolean flag = false;
        Schedule add = BeanUtil.toBean(bo, Schedule.class);
        CarrierVo carrierVo = carrierMapper.selectCarrierVoByID(add.getCarrierId());
        validEntityBeforeSave(add);

        Date sday = DateUtils.string2Date(bo.getDateList().get(0), "yyyy-MM-dd");//开始时间
        Date eday = DateUtils.string2Date(bo.getDateList().get(1), "yyyy-MM-dd");//到期时间
        int days = DateUtils.differentDaysByMillisecond(sday,eday)+1;//获取相差日期

        //星期
        String weeks = StringUtils.join(bo.getWeeks(),",");

        Calendar cal = Calendar.getInstance();
        cal.setTime(sday);//设置初始时间

        for (int i = 0;i<days;i++){
            //获取初始时间
            Date now = cal.getTime();

            //获取初始时间是星期几
            Integer week = cal.get(Calendar.DAY_OF_WEEK);
            //判断设置时间是否属于weeks区间内，不属于则跳出循环
            if(!weeks.contains(String.valueOf(week))){
                cal.add(Calendar.DAY_OF_YEAR, 1);
                continue;
            }

            //获取当前时间是否安排车次
//            ScheduleBo scheduleBo = new ScheduleBo();
//            scheduleBo.setDay(now);
//            scheduleBo.setLineId(add.getLineId());
//            List<ScheduleVo> handles = baseMapper.selectScheduleList(scheduleBo);
//            if(handles == null && handles.size() == 0){
//
//            }
            //填充UUID
            add.setId(IdUtil.simpleUUID());
            add.setDelFlag("0");
            add.setStatus("0");
            add.setDay(now);
            add.setDeptId(carrierVo.getDeptId());
            flag = baseMapper.insert(add) > 0;
            if (flag) {
                bo.setId(add.getId());
            }
            if(bo.getItems() != null && bo.getItems().size() > 0){
                for (ScheduleDtlVo dtl:bo.getItems()){
                    dtl.setId(IdUtil.simpleUUID());
                    dtl.setDelFlag("0");
                    dtl.setScheduleId(add.getId());
                    dtl.setCarNumber(carMapper.selectCarVoByID(dtl.getCarId()).getCarNumber());
                    dtl.setDriverName(driverMapper.selectDriverVoByID(dtl.getDriverId()).getPersonName());
                    ScheduleDtl scheduleDtl = new ScheduleDtl();
                    BeanUtil.copyProperties(dtl,scheduleDtl);
                    scheduleDtlMapper.insertOrUpdate(scheduleDtl);
                }
            }
            //根据循环往前推进1天
            cal.add(Calendar.DAY_OF_YEAR, 1);
        }

        return flag;
    }

    /**
     * 修改车次
     *
     * @param bo 车次
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateByBo(ScheduleBo bo) {
        Schedule update = BeanUtil.toBean(bo, Schedule.class);
        validEntityBeforeSave(update);

        if(bo.getItems() != null && bo.getItems().size() > 0){
            for (ScheduleDtlVo dtl:bo.getItems()){
                if(StringUtils.isEmpty(dtl.getId())){
                    dtl.setId(IdUtil.simpleUUID());
                }
                dtl.setDelFlag("0");
                dtl.setScheduleId(update.getId());
                dtl.setCarNumber(carMapper.selectCarVoByID(dtl.getCarId()).getCarNumber());
                dtl.setDriverName(driverMapper.selectDriverVoByID(dtl.getDriverId()).getPersonName());
                ScheduleDtl scheduleDtl = new ScheduleDtl();
                BeanUtil.copyProperties(dtl,scheduleDtl);
                scheduleDtlMapper.insertOrUpdate(scheduleDtl);
            }
        }

        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(Schedule entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除车次
     *
     * @param ids 需要删除的车次主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
